
/*
	Copyright 2012 Morten Knudsen

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.

*/
package main

import (
	"archive/zip"
"fmt"
 "os"
	"path"
 "path/filepath"
 "strings"
)
func main() {
	l := len(os.Args)
	if l < 2 || l > 3 {
		fmt.Printf("Wrong numbers of arguments %d:\nUsage: mochahunter className [directory]\n",l)
		return
	}
	classname := os.Args[1]
	
	if !strings.HasSuffix(classname,".class") {
		classname = classname+ ".class"
	}
	path, _ := os.Getwd() 
	if l==3 {
		path = os.Args[2]
	}
	fmt.Printf("Searching for %s in %s\n", classname, path)
	FindClass(path, classname)
}



func ScanJar(fullpath string, classname string) {
	r, err := zip.OpenReader(fullpath)
	if err != nil {
		fmt.Printf("%s : %s\n",err,fullpath)
		return
	}
	defer r.Close()
	
	// Iterate through the files in the archive,
	// printing some of their contents.
	for _, f := range r.File {
		if strings.HasSuffix(f.Name, classname)  {
			if f.Name == classname || strings.HasSuffix(f.Name, "/"+classname) {
				fmt.Printf("Found %s in %s\n",f.Name,fullpath)
			}
		}
		
	}

	
}

func FindClass(root string, classname string) {
 jarfinder := func(fullpath string, info os.FileInfo, err error) error {
 name := path.Base(fullpath)
 if strings.HasSuffix(name,".jar") {
	ScanJar(fullpath, classname) 
 }
 return nil
 }
 
	
  filepath.Walk(root, jarfinder)
}